import { savePermissionApi, updatePermissionApi } from '@/services/api';
import {
  DrawerForm,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import { Form, message } from 'antd';
import { isEqual } from 'lodash';
import React, { useEffect, useRef } from 'react';
interface Props {
  open?: boolean;
  info?: any;
  close?: () => void;
  onFinsh?: () => void;
}
// 新增/编辑用户
const CreateAuthCodeConfig: React.FC<Props> = ({
  open,
  close,
  info,
  onFinsh,
}) => {
  const [form] = Form.useForm<{ name: string; company: string }>();

  const formRef = useRef<ProFormInstance>();

  useEffect(() => {
    if (info) {
      setTimeout(() => {
        formRef?.current?.setFieldsValue({
          ...info,
        });
      }, 20);
    }
  }, [info]);

  return (
    <DrawerForm
      formRef={formRef}
      title={info.id ? '编辑' : '新建'}
      form={form}
      open={open}
      width={'38%'}
      onOpenChange={(visible) => {
        if (!visible) {
          close?.();
        }
      }}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
      }}
      onFinish={async (values) => {
        try {
          if (info?.id) {
            await updatePermissionApi(info?.id, {
              ...values,
            });
            message.success('修改成功');
            onFinsh?.();
            // 不返回不会关闭弹框
            return true;
          } else {
            await savePermissionApi({
              ...values,
            });

            message.success('添加成功');
            onFinsh?.();
            // 不返回不会关闭弹框
            return true;
          }
        } catch (error) {}
      }}
    >
      <ProFormText
        name="title"
        label="权限名称"
        rules={[{ required: true, message: '请输入权限名称' }]}
      ></ProFormText>

      <ProFormText
        name="code"
        label="权限码"
        rules={[{ required: true, message: '请输入权限码' }]}
      ></ProFormText>
    </DrawerForm>
  );
};

export default React.memo(CreateAuthCodeConfig, (prev, next) =>
  isEqual(prev, next),
);
